<template>
  <el-card class="form-container" shadow="never">
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="填写商品信息"></el-step>
      <el-step title="填写商品促销"></el-step>
      <el-step title="填写商品属性"></el-step>
      <el-step title="选择商品关联"></el-step>
    </el-steps>
    <ProductInfoDetail v-show="active === 0" v-model="productParam" :is-edit="!!route.query.id" @nextStep="nextStep" />
    <ProductSaleDetail v-show="active === 1" v-model="productParam" :is-edit="route.query.id" @nextStep="nextStep" @prevStep="prevStep" />
    <ProductAttrDetail v-show="active === 2" v-model="productParam" :is-edit="!!route.query.id" @nextStep="nextStep" @prevStep="prevStep" />
    <ProductRelationDetail
      v-show="active === 3"
      v-model="productParam"
      :is-edit="route.query.id"
      @prevStep="prevStep"
      @finishCommit="finishCommit"
    />
  </el-card>
</template>
<script setup lang="ts">
import ProductInfoDetail from './components/ProductInfoDetail.vue'
import ProductSaleDetail from './components/ProductSaleDetail.vue'
import ProductAttrDetail from './components/ProductAttrDetail.vue'
import ProductRelationDetail from './components/ProductRelationDetail.vue'
import { createProduct, getProduct, updateProduct } from '@/api/product'
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import type { ProductDetail } from '@/models/product'

defineOptions({ name: 'ProductDetail' })
const route = useRoute()
const router = useRouter()
const active = ref(0)
const productParam = ref<ProductDetail>({
  memberPriceList: [],
  productFullReductionList: [{ fullPrice: 0, reducePrice: 0 }],
  productLadderList: [{ count: 0, discount: 0, price: 0 }],
  productAttributeValueList: [],
  skuStockList: [],
  subjectProductRelationList: [],
  prefrenceAreaProductRelationList: [],
})

onMounted(async () => {
  if (route.query.id) {
    const response = await getProduct(Number(route.query.id))
    const data = response.data.data
    data?.skuStockList?.forEach((item) => {
      item.spData = JSON.parse(item?.spData || '[]')
    })
    productParam.value = data
  }
})
function prevStep() {
  active.value = active.value > 0 ? active.value - 1 : 0
}
function nextStep() {
  active.value = active.value < 3 ? active.value + 1 : 3
}
async function finishCommit() {
  productParam.value?.skuStockList?.forEach((item) => {
    item.spData = JSON.stringify(item?.spData)
  })
  if (productParam.value.id) {
    await updateProduct(productParam.value)
  } else {
    await createProduct(productParam.value)
  }
  ElMessage.success('提交成功')
  router.back()
}
</script>
<style>
.form-container {
  width: 960px;
}

.form-inner-container {
  width: 800px;
}
</style>
